<template>
  <div class="oss-upload">
    <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="initConfig" :http-request="handleUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import axios from "axios";
import uuid from "uuid/v4";
export default {
  data() {
    return {
      token: {},
      client: null,
      // region: 'oss-cn-shenzhen',
      // bucket: 'tidc-drive',
      // path: '/'
    };
  },
  props: {
    region: String,
    bucket: String,
    path: {
      type: String,
      default: ""
    },
    ossTokenUrl: String,
    randomName: {
      type: Boolean,
      default: true
    },
    imageUrl: String
  },
  methods: {
    // handleAvatarSuccess(res, file) {

    // },
    verifyFile(file) {
      const isImage = file.type.indexOf("image") !== -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isImage && isLt2M;
    },
    async initConfig(file) {
      if (!this.verifyFile(file)) {
        return false;
      }

      let { data } = await axios({ url: this.ossTokenUrl, method: "get" });
      data = data.data;

      this.client = new OSS.Wrapper({
        region: this.region,
        accessKeyId: data.accessKeyId,
        accessKeySecret: data.accessKeySecret,
        stsToken: data.securityToken,
        bucket: this.bucket
      });
      return true;
    },
    async handleUpload(params) {
      const { file } = params;
      // console.log(file.name, file.size);
      // const { name, size } = file;
      try {
        const result = await this.client.multipartUpload(`${this.path}/${uuid()}`, file);
        // console.log(result);
        this.$emit("success", result.res.requestUrls[0].split("?")[0]);
      } catch (error) {
        this.$emit("failed", error);
      }
    }
  }
};
</script>

<style lang="scss">
.oss-upload {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>